package com.tticar.invmanager.tticar.service.impl;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tticar.invmanager.common.Enum.CodeType;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.shiro.MySecurityUtils;
import com.tticar.invmanager.common.utils.ServiceUtil;
import com.tticar.invmanager.entity.*;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.mapper.WStoreMapper;
import com.tticar.invmanager.service.*;
import com.tticar.invmanager.tticar.entity.Goods;
import com.tticar.invmanager.tticar.entity.GoodsProduction;
import com.tticar.invmanager.tticar.entity.Pictures;
import com.tticar.invmanager.tticar.entity.Store;
import com.tticar.invmanager.tticar.mapper.StoreMapper;
import com.tticar.invmanager.tticar.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 店铺表 服务实现类
 * </p>
 *
 * @author joeyYan
 * @since 2018-07-24
 */
@Service
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements IStoreService {

    @Autowired
    private ICodeCounterService codeCounterService;
    @Autowired
    ISysTenantService sysTenantService;
    @Autowired
    private IWStoreService wStoreService;
    @Autowired
    IStoreOwnerService storeOwnerService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsProductionService goodsProductionService;
    @Autowired
    private IMMaterielService materielService;
    @Autowired
    private IMMaterielSkuService materielSkuService;
    @Autowired
    private IMMaterielTticarService materielTticarService;
    @Autowired
    private IPicturesService picturesService;
    @Autowired
    private ISysPictrueService sysPictrueService;
    @Autowired
    private WStoreMapper wStoreMapper;
    
    @Override
    public List<Store> selectList() {
        // 先获取当前租户
        // 再根据当前用户租户的手机号匹配天天爱车店铺
//        SysTenant tenant = sysTenantService.selectById(tenantId);
//        Wrapper wrapper = new EntityWrapper<>();
//        wrapper.eq("mobile", tenant.getMobile());
//        com.tticar.invmanager.tticar.entity.StoreOwner storeOwner = storeOwnerService.selectOne(wrapper);
//        if (storeOwner == null) {
//            return null;
//        }
        List<Long> longs = wStoreMapper.queryStoreBelongUser(/*ServiceUtil.getLoginUser().getUsername()*/);
        if (longs == null || longs.size() < 1) {
            return null;
        }
        Wrapper w = new EntityWrapper<>();
        w.in("id", longs);
        return this.selectList(w);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyStore(String mobile) {
        Wrapper w = Condition.create().eq(Store.TEL, mobile);
        // 关联天天爱车商铺id
        List<Store> stores = this.selectList(w);
        if (CollectionUtils.isEmpty(stores)) {
            throw MyServiceException.getInstance("未匹配到天天爱车店铺，请核实号码是否正确。");
        }
        Wrapper<WStore> wStoreWrapper = new EntityWrapper<WStore>().eq(WStore.MOBILE, mobile);
        WStore wStore = new WStore();
        wStore.setTtstoreId(stores.get(0).getId());
        wStoreService.update(wStore, wStoreWrapper);
        // 同步天天爱车产品到库存管理存货商品
        Wrapper wrapper = Condition.create().eq(Goods.STOREID, stores.get(0).getId());
        wrapper.eq("status", 0);
        List<Goods> goodslist = goodsService.selectList(wrapper);
        for (Goods goods : goodslist) {
//            if (goods.getStatus() != 0) continue;
            String pics = insertPics(goods.getId()); // 1
            Long mid = insertMateriel(goods, pics); // 2
            String skus = insertMskus(goods.getId(), mid); // 3

            MMaterielTticar mt = new MMaterielTticar();
            mt.setCuser(MySecurityUtils.currentUser().getUsername());
            mt.setTtstoreId(stores.get(0).getId());
            mt.setTtgoodsId(goods.getId());
            mt.setMaterielId(mid);
            mt.setMaterielSkuIds(skus);
            mt.setPictrues(pics);
            materielTticarService.insert(mt); // 4
        }
    }

    private String insertMskus(Long goodsId, Long mid) {
        List<GoodsProduction> gplist = goodsProductionService.selectList(Condition.create().eq(GoodsProduction.GOODID, goodsId));
        if (gplist.isEmpty()) {
            return "";
        }
        List mskus = new ArrayList();
        for (GoodsProduction goodsProduction : gplist) {
            MMaterielSku msku = new MMaterielSku();
            msku.setMid(mid);
            msku.setPrices(goodsProduction.getSkuPic());
//            msku.setInventory(Double.valueOf(goodsProduction.getInventory()));
            msku.setSkus(goodsProduction.getName());
            msku.setStatus(1);
            // 这里没有分类 暂时默认“00”
            String code = codeCounterService.getCode(CodeType.SP, "00", 5);
            msku.setCode(code);
            materielSkuService.insert(msku);
            mskus.add(msku.getId());
        }

        return mskus.toString().replace("[", "").replace("]", "");
    }

    private String insertPics(Long goodsId) {
        Wrapper pw = Condition.create().eq(Pictures.REFID, goodsId).eq(Pictures.TYPE, 1).orderBy(Pictures.SORT, false);
        List<Pictures> piclist = picturesService.selectList(pw);
        if (piclist.isEmpty()) {
            return "";
        }
        List<Long> list = new ArrayList();
        for (Pictures pictures : piclist) {
            SysPictrue pic = new SysPictrue();
            pic.setPid(getTTicarPack());
            pic.setPath(pictures.getPath());
            pic.setType(SysPictrue.ONE);
            pic.setName(pictures.getId() + "");
            pic.setCuser(MySecurityUtils.currentUser().getUsername());
            sysPictrueService.insert(pic);
            list.add(pic.getId());
        }
        return list.toString().replace("[", "").replace("]", "");
    }

    private Long getTTicarPack() {
        List<SysPictrue> list = sysPictrueService.selectList(Condition.create().eq(SysPictrue.TYPE, SysPictrue.ZERO).eq(SysPictrue.NAME, "天天爱车"));
        if (list.isEmpty()) {
            SysPictrue pic = new SysPictrue();
            pic.setPid(0l);
            pic.setName("天天爱车");
            pic.setType(SysPictrue.ZERO);
            pic.setMemo("天天爱车同步的产品的图片");
            pic.setCuser(MySecurityUtils.currentUser().getUsername());
            sysPictrueService.insert(pic);
            return pic.getId();
        } else {
            return list.get(0).getId();
        }
    }

    private Long insertMateriel(Goods goods, String pics) {
        MMateriel m = new MMateriel();
        m.setName(goods.getName());
//        m.setNameSpell(goods.getNameSpell());
        m.setCode(goods.getGoodNo());
        m.setDescription(goods.getDescription());
        m.setStatus(1);
//        m.setAinventory(Float.valueOf(goods.getInventory()));
        m.setPictrues(pics);
        materielService.insert(m);
        return m.getId();
    }

    @Override
    public List category(String name, Long id) {
        Wrapper w = Condition.create();
        w.like(StringUtils.hasText(name), "name", name);
        if (org.apache.commons.lang3.StringUtils.isBlank(name)) {
            w.eq("parentId", id == 0 ? -1 : id);
        }

        List<Map> list = goodsService.category(w);
        return list;
    }

    @Override
    public Page brand(String name, MyPage page) {
        Wrapper w = Condition.create();
        w.like(StringUtils.hasText(name), "name", name);
        List list = goodsService.brand(page, w);
        page.setRecords(list);
        return page;
    }

    @Override
    public Page pushlet(Page page, String ptype, Long storeId) {
        List<Map> list = new ArrayList();

        switch (ptype) {
            case "goods_visit":
                list = baseMapper.visitGoods(page, storeId);
                break;
            case "store_visit":
                list = baseMapper.visitStore(page, storeId);
                break;
            case "call_visit":
                list = baseMapper.visitCall(page, storeId, 1);
                break;
            case "chat_visit":
                list = baseMapper.visitCall(page, storeId, 2);
                break;
            case "order_visit":
                list = baseMapper.visitOrder(page, storeId);
                break;
        }

        return page.setRecords(list);
    }

}
